<template>
    <a-modal v-model:open="open" title="发布内容" width="100%" height="600px" wrap-class-name="full-modal" @ok="handleOk">
        <div style="border: 1px solid #ccc">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
                :mode="mode" @onCreated="handleCreated" />
        </div>
    </a-modal>
</template>
<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar,InsertFnType } from '@wangeditor/editor-for-vue'
// 控制对话框显示状态
const open = ref<boolean>(false);
// 切换对话框显示状态
const showModal = () => {
    open.value = !open.value;
};

const handleOk = (e: MouseEvent) => {
    console.log(e);
    open.value = false;
};

// 富文本编辑器模式,可选值 default:默认模式 simple:简单模式
const mode = "default"
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    }, 1500)
})

const toolbarConfig = {}
const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            fieldName: 'img',
            meta: {
                // 额外参数
            },
            // 图片上传地址
            server: 'http://localhost:3000/api/imgUpload',
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            customInsert(res: any, insertFn: InsertFnType) {
                // TS 语法
                // customInsert(res, insertFn) {                  // JS 语法
                // res 即服务端的返回结果
                // 从 res 中找到 url alt href ，然后插入图片
                insertFn(`http://localhost:3000`+res.data, '', '#')
            },
        }
    }
}


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

defineExpose({ showModal })
</script>
<style lang="scss">
.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;
    }

    .ant-modal-content {
        display: flex;
        flex-direction: column;
        // height: calc(100vh);
    }

    .ant-modal-body {
        flex: 1;
    }
}
</style>